package com.huangliusong.web.http.converter.properties;


import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractGenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.*;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Properties;

/**
 * @author huangliusong
 * @since 2018/10/4
 * {@link }
 */
public class PropertiesHttpMessageConverter extends AbstractGenericHttpMessageConverter<Properties> {

    public PropertiesHttpMessageConverter() {
        super(new MediaType("text","properties"));
    }

    @Override
    protected void writeInternal(Properties properties, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        //properties->String
        //outputstream->writer


        //字符流 字符编码
        //请求头解析字符编码
        HttpHeaders httpHeaders=outputMessage.getHeaders();
        MediaType mediaType=httpHeaders.getContentType();
        //获取字符编码
        Charset charset =mediaType.getCharset();
        //不存在时
        charset=charset==null?Charset.forName("UTF-8"):charset;
        //字节输出流
        OutputStream outputStream=outputMessage.getBody();
        //字符输出流
        Writer writer=new OutputStreamWriter(outputStream,charset);


        //Properties write to
        properties.store(writer,"注释内容");
    }

    @Override
    protected Properties readInternal(Class<? extends Properties> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

        //字符流 字符编码
        //请求头解析字符编码
        HttpHeaders httpHeaders=inputMessage.getHeaders();
        MediaType mediaType=httpHeaders.getContentType();
        //获取字符编码
        Charset charset =mediaType.getCharset();
        //不存在时
        charset=charset==null?Charset.forName("UTF-8"):charset;

        //字节流
        InputStream inputStream=inputMessage.getBody();
        //　字节流
        InputStreamReader reader=new InputStreamReader(inputStream,charset);

        Properties properties=new Properties();
        //加载字符流　
        properties.load(reader);
        return properties;
    }

    @Override
    public Properties read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return readInternal(null,inputMessage);
    }
}
